import React, { Component } from 'react';
import _ from 'lodash';
import {
  StyleSheet, View, Text, TouchableOpacity, Modal, FlatList, TextInput,
} from 'react-native';
import produce from 'immer';
import { Icon } from 'native-base';
import {
  ListFooter, BlankBackground, Loading,
} from './index';
import * as todoService from '../services/todo';

export default class FormThinkTextview extends Component {
  page = 1; // 分页请求的当前页数

  startPosition = 0; // 开始滑动的位置

  index = 0; // 记录当前page的index

  searchValue = '';

  constructor(props) {
    super(props);
    this.state = {
      list: [],
      refreshing: false,
      isMore: false,
      isError: false,
      showLoading: true,
      text: '',
    };
  }

  componentDidMount() {
    this._onInitRefresh();
  }

  fetchList = async (payload) => {
    try {
      this.setState({ isError: false });
      const currPage = this.page + 1;
      const { list, page, total } = await todoService.choiceSearch({ ...payload, page: currPage }, this.props.searchUri);

      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list.push(...list);
        this.page = page;
        draft.isMore = draft.list.length < total;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true });
    }
  }

  refreshList = async (payload) => {
    try {
      this.setState({ isError: false });
      const { list, page, total } = await todoService.choiceSearch({ ...payload, page: 1 }, this.props.searchUri);
      const isMore = list.length < total;
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list = list;
        draft.refreshing = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
    }
  }

  initRefreshList = async (payload) => {
    try {
      this.setState({ showLoading: true, isError: false, list: [] });
      const { list, page, total } = await todoService.choiceSearch({ ...payload, page: 1 }, this.props.searchUri);
      const isMore = list.length < total;
      this.setState(produce(draft => {
        draft.list = list;
        draft.showLoading = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, showLoading: false });
    }
  }

  // 刷新时候获取数据
  _onRefresh = () => {
    this.refreshList({ condition: this.searchValue });
  }

  // 初始化的时候获取数据
  _onInitRefresh = () => {
    this.initRefreshList({ condition: this.searchValue });
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.fetchList({ condition: this.searchValue });
    }
  }

  _onItemClick = (item) => {
    let list = [];
    if (this.props.type === 'radio') { //单选
      list = this.state.list.map((it, index) => ({
        ...it,
        checked: index === item.index,
      }));
      this.setState(produce(draft => {
        draft.list = list;
      }));
    } else { // 多选
      this.setState(produce(draft => {
        draft.list[item.index].checked = !draft.list[item.index].checked;
      }));
    }

  }

  // 列表的item组件
  _renderItem = (item) => (
    <TouchableOpacity
      style={{ padding: 10, justifyContent: 'space-between', flexDirection: 'row' }}
      onPress={() => this._onItemClick(item)}
    >
      <Text>
        {item.item.name}
      </Text>
      <Icon name="check" type="MaterialIcons" style={{ color: item.item.checked ? 'blue' : 'gray' }} />
    </TouchableOpacity>
  );

  // 列表的分割线
  _renderItemSeparator = () => (
    <View style={{ height: 0.5, backgroundColor: '#EDF5FA' }} />
  )

  // 列表上拉加载的组件
  _renderListFooter = () => (
    (this.state.list.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  _onSearch = async (searchValue) => {
    this.searchValue = searchValue;
    this.initRefreshList({ condition: this.searchValue });
  }

  choiceConfirm = () => {
    const list = this.state.list.filter((it) => (it.checked));
    if (list && list.length > 0) {
      this.props.choiceConfirm(list);
      this.props.onClose();
    } else {
      alert('请至少选择一个');
    }
  };

  render() {
    const {
      onClose,
    } = this.props;

    const {
      showLoading, isError, list, refreshing,
    } = this.state;

    let mView = <Loading />;
    if (!showLoading) {
      if (list.length === 0) {
        mView = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
      } else {
        mView = (
          <FlatList
            renderItem={this._renderItem}
            data={list}
            keyExtractor={(item, index) => item + index}
            onRefresh={this._onRefresh}
            refreshing={refreshing}
            onEndReachedThreshold={0.05}
            onEndReached={this._onEndReached}
            ListFooterComponent={this._renderListFooter}
            ItemSeparatorComponent={this._renderItemSeparator}
          />
        );
      }
    }

    return (
      <Modal
        animationType="none"
        transparent={false}
        onRequestClose={onClose}
        style={styles.modal}
      >
        <View style={styles.input_container}>
          <TextInput
            style={styles.textArea}
            numberOfLines={3}
            multiline
            onChangeText={(text) => this.setState({ text })}
            value={this.state.text}
          />
          <TouchableOpacity
            style={{ padding: 10 }}
            onPress={() => alert('确定')}
          >
            <Text>确定</Text>
          </TouchableOpacity>
        </View>
        <View style={{ flex: 1 }}>
          {mView}
        </View>
      </Modal>
    );
  }
}

const styles = StyleSheet.create({
  modalConteniner: {
    width: '100%',
    height: '100%',
  },
  record_text: {
    paddingLeft: 10,
    paddingBottom: 10,
    fontSize: 12,
  },
  record_text_container: {
    padding: 10,
    flex: 1,
  },
  record_text_bg: {
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: '#DEE1E6',
    backgroundColor: '#fff',
  },
  clear_text_bg: {
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: '#DEE1E6',
    textAlign: 'center',
    fontSize: 12,
  },
  footer: {
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
    height: 48,
    borderTopWidth: 0.5,
    borderTopColor: 'rgba(0,0,0,0.5)',
  },
  input_container: {
    padding: 10,
    flexDirection: 'row',
    alignItems: 'center',
    width: '100%',
  },
  textArea: {
    padding: 10,
    margin: 5,
    backgroundColor: 'white',
    textAlignVertical: 'top',
    borderRadius: 5,
    flex: 1,
  },
});
